/*
 * Project Name spring-boot-tools
 * File Name LoadGateway
 * Package Name com.huxiaosu.tools.cmpp
 * Create Time 2024/5/19
 * Create by name：liujie
 */
package com.huxiaosu.tools.cmpp;

import com.huxiaosu.tools.cmpp.action.MessageHandler;
import com.huxiaosu.tools.cmpp.cache.CacheService;
import com.huxiaosu.tools.cmpp.codec.CodecFactory;
import com.huxiaosu.tools.cmpp.config.CmppClientConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.context.WebServerInitializedEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.scheduling.annotation.Async;

import java.net.InetSocketAddress;

/**
 * Description
 *
 * @author liujie
 * @date 2024/5/19 11:04
 */
@Slf4j
@Configuration(proxyBeanMethods = false)
public class LoadGateway {
    @Autowired
    private CacheService cacheService;
    @Autowired
    private CmppClientConfig cmppClientConfig;
    @Async
    @Order
    @EventListener(WebServerInitializedEvent.class)
    public void afterStart(WebServerInitializedEvent event) {
        String spId = cmppClientConfig.getSpId();
        NioSocketConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new CodecFactory("UTF-8")));

        // 设置连接超时检查时间
        connector.setConnectTimeoutCheckInterval(30);
        connector.setHandler(new MessageHandler());

        // 建立连接
        log.info("connection server ip={},port = {}", cmppClientConfig.getSpIp(), cmppClientConfig.getPort());
        ConnectFuture cf = connector
                .connect(new InetSocketAddress(cmppClientConfig.getSpIp(), cmppClientConfig.getPort()));
        // 等待连接创建完成
        cf.awaitUninterruptibly();
        IoSession serverSession = cf.getSession();
        cacheService.put(spId,serverSession);
    }
}
